package com.rk.kbk.controller.core;


import com.alibaba.fastjson.JSONObject;
import com.rk.kbk.common.*;
import com.rk.kbk.controller.push.JpushClientUtil;
import com.rk.kbk.controller.push.JpushShopClientUtil;
import com.rk.kbk.dao.*;
import com.rk.kbk.dto.PageDto;
import com.rk.kbk.model.*;
import com.rk.kbk.service.OrderService;
import com.rk.kbk.service.UserService;
import com.rk.kbk.sms.SmsUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.json.JSONArray;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/user")
public class UserController {
	private Logger log = Logger.getLogger(this.getClass());
	@Autowired
	private UserDao userDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private CashRecordDao cashRecordDao;
	@Autowired
	private UserService userService;
	@Autowired
	private OrderService orderService;
    @Autowired
    private AddressDao addressDao;
	@Autowired
	private SendRatesDao sendRatesDao;
	@PersistenceContext
	private EntityManager entityManager;
	@Autowired
	private SortBetweenDao sortBetweenDao;
	@Autowired
	private AccountDao accountDao;
	@Autowired
	private SortTypeDao sortTypeDao;
	@Autowired
	private SqlToResult sqlToResult;
    @Autowired
    private UserLeaveDao userLeaveDao;
	@Autowired
	private WorkLogDao workLogDao;
	@Autowired
	private OpenAreaDao openAreaDao;
	@Autowired
	private CallSettingDao callSettingDao;
	private  ScheduledExecutorService service=null;
	/**
	 * 注册/修改
	 * @param user 用户
	 * @return JsonResp
	 */
	@RequestMapping(value = "/register",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp register(@RequestBody User user){
		Long id = user.getId();
		if (id == null) {
			log.debug("注册");
			User user0 = userDao.findOneByPhone(user.getPhone());
			if (user0 != null) {
				throw new FailException("用户名已存在");
			}
			user.setPassword(Md5.md5Encode(user.getPassword()));
			userDao.save(user);
			return JsonResp.ok(user);
		}
		log.debug("用户修改信息");
		User user0 = userDao.findOneByPhoneAndIdNot(user.getPhone(), user.getId());
		if (user0 != null) {
			throw new FailException("用户名已存在");
		}
		user.setPassword(userDao.findOne(user.getId()).getPassword());
		userDao.save(user);
		return JsonResp.ok(user);
	}
	
	/**
	 * 登录
	 * @param name 用户名
	 * @param password 密码
	 * @return JsonResp
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/login",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp login(String name, String password) throws UnsupportedEncodingException {
		log.debug("登录");
		return userService.login(URLDecoder.decode(name,"utf-8"), password);
	}

	/**
	 * 发送短信
	 * @param phone 用户名
	 * @param userType 用户类型，2表示骑手，3表示商家
	 * @return JsonResp
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/sendsms",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp  sendsms(String phone,Integer userType) throws Exception {
		log.debug("获取登录验证码");
        String templateid="";
        if(userType==2){//骑手登录获取验证码
            templateid="3049408";
        }else if(userType==3){//商家登录获取验证码
            templateid="3056317";
        }else if(userType==4){//骑手提现获取验证码
            templateid="3062219";
			userType=2;
        }else if(userType==5){//商家提现获取验证码
            templateid="3061300";
        }else if(userType==6){//商家更改账号获取验证码
            templateid="3049411";
        }
		String code = SmsUtils.sendCode(phone, userType,templateid);
		if(!"".equals(code)){
			return JsonResp.ok("成功！");
		}else{
			return JsonResp.fa("获取验证码失败！");
		}
	}



	/**
	 * 发送短信(微信端)
	 * @param phone 用户名
	 * @return JsonResp
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/sendCode",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp sendCode(String phone) throws Exception {
		log.debug("获取登录验证码");
		String code = SmsUtils.sendCode(phone, 1,"");
		if(!"".equals(code)){
			return JsonResp.ok("成功");
		}else{
			return JsonResp.fa("获取验证码失败！");
		}
	}


	/**
	 * 短信登录
	 * @param phone 用户名
	 * @param code 验证码
	 * @param userType 用户类型，2表示骑手，3表示商家
	 * @return JsonResp
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/loginsms",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp loginsms(String phone, String code,Integer userType,String alias,String source,Long userId) throws UnsupportedEncodingException {
		log.debug("登录");
		return userService.loginSms(URLDecoder.decode(phone,"utf-8"), code,userType,alias,source,userId);
}

	/**
	 * 注销
	 */
	@RequestMapping(value = "/logout",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp logout(){
		log.debug("注销");
		userService.logout();
		return JsonResp.ok();
	}

	/**
	 * 商家为骑手评价
	 */
	@RequestMapping(value = "/evaluateRide",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp evaluateRide(Long orderId,int isOk) {
		log.debug("商家为骑手评价");
		Order order = orderDao.findOne(orderId);
		if (order.getIsOk() != null) {
			return JsonResp.fa("已评价，请勿重复操作");
		} else {
			order.setIsOk(isOk);
			orderDao.save(order);
			return JsonResp.ok();
		}

	}
	
	/**
	 * 获取用户详情-ByUserId
	 * @param userId 用户id
	 * @return JsonResp
	 */
	@RequestMapping(value = "/userDetails",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp findUserDetByUserId(Long userId) {
		log.debug("获取用户详情-ByUserId");
		return JsonResp.ok(userDao.findOne(userId));
	}

	/**
	 * 获取用户账户详情-ByUserId
	 * @param userId 用户id
	 * @return JsonResp
	 */
	@RequestMapping(value = "/account2Details",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp findUserDet2ByUserId(Long userId) {
		log.debug("获取用户详情-ByUserId");
		User user=userDao.findOne(userId);
		return JsonResp.ok(accountDao.findByUser(user));
	}

	/**
	 * 获取当前登陆用户
	 * @return JsonResp
	 */
	@RequestMapping(value = "/findLoginUser",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp findLoginUser() {
		log.debug("获取当前登陆用户");
		return JsonResp.ok(userService.findLoginUser());
	}
	
	/**
	 * 获取用户总数
	 * @return JsonResp
	 */
	@RequestMapping(value = "/AllUserNumber",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp findAllUserNumber() throws JSONException {
		log.debug("获取用户总数");
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("userNumber", userDao.findAll().size()+"");
		return JsonResp.ok(jsonObject);
	}




	/**
	 * 商家为骑手评价
	 * @return JsonResp
	 */
	@RequestMapping(value = "/estimateRide",
			method = RequestMethod.POST,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp estimateRide() throws JSONException {
		log.debug("商家为骑手评价");
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("userNumber", userDao.findAll().size()+"");
		return JsonResp.ok(jsonObject);
	}


	/**
     * 分页查询(原生sql方式)
     * @param user 分页条件
     * @param pageNum 第几页
     * @param pageSize 每页条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/sql/page/{pageNum}/{pageSize}",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageUserSql(@RequestBody(required = false) User user, @PathVariable Integer pageNum, @PathVariable Integer pageSize) {
		log.debug("分页查询(原生sql方式)");
		String sql = "FROM user WHERE 1=1 ";
		if (user != null && !StringUtils.isBlank(user.getPhone())) {
			sql += "AND phone LIKE '%"+user.getPhone()+"%' ";
		}
		sql += "ORDER BY gmt_datetime DESC ";

		Query query = entityManager.createNativeQuery("SELECT * " + sql, User.class);
		BigInteger count_number = null;
		//总记录数
		Query query_number = entityManager.createNativeQuery("SELECT COUNT(1) " + sql);
		count_number = (BigInteger) query_number.getSingleResult();
		long total = count_number.longValue();
		//分页
		if ((pageNum-1) >= 0) {
			query.setFirstResult((pageNum-1) * pageSize);
		}
		if (pageSize > 0) {
			query.setMaxResults(pageSize);
		}
		entityManager.close();
		List resultList = query.getResultList();
		return JsonResp.ok(new PageDto(pageNum, pageSize, resultList, total));
    }


	/**
	 * @商家上传餐饮许可证
	 * @param shopId
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/upLoadLicenseUrl",
			method = RequestMethod.POST,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp upLoadLicenseUrl(Long  shopId,String licenseUrl) {
		log.debug("商家上传餐饮许可证");
		User user=userDao.findOne(shopId);
		user.setLicenseUrl(licenseUrl);
        user.setLicenseUrlStatus(1);
		userDao.save(user);
		return JsonResp.ok();
	}
	/**
	 * 上传健康证（骑手）
	 * @param rideId
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/upLoadHealthCard",
			method = RequestMethod.POST,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp upLoadHealthCard(Long  rideId,String healthCard) {
		log.debug("商家上传餐饮许可证");
		User user=userDao.findOne(rideId);
		user.setLicenseUrl(healthCard);
		user.setHealthCardStatus(1);
		userDao.save(user);
		return JsonResp.ok();
	}


	/**
	 * @商家设置出货时间
	 * @param shopId
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/setShopStartTime",
			method = RequestMethod.POST,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp setShopStartTime(Long  shopId,String shopStartTime) {
		log.debug("商家上传餐饮许可证");
		User user=userDao.findOne(shopId);
		user.setShopStartTime(shopStartTime);
		userDao.save(user);
		return JsonResp.ok();
	}

	/**
	 * @语音提示
	 * @param userId
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/setVoicePrompt",
			method = RequestMethod.POST,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp setVoicePrompt(Long  userId,int voiceType) {
		log.debug("商家上传餐饮许可证");
		User user=userDao.findOne(userId);
		user.setVoice(voiceType);
		userDao.save(user);
		return JsonResp.ok();
	}


	/**
	 * @手机号修改（输入原手机号 验证码验证）
	 * @param code
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/checkOriginalPhone",
			method = RequestMethod.POST,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp checkOriginalPhone(String originalPhone,String code,int userType) throws Exception {
		log.debug("手机号修改（输入原手机号 验证码验证）");
			Boolean aBoolean = SmsUtils.checkCode(originalPhone, code, userType);
			if(aBoolean){
				return JsonResp.ok("验证通过");
			}else {
				return JsonResp.fa("验证码错误！");
			}
	}


	/**
	 * @手机号修改（输入新手机号 验证码验证）
	 * @param code
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/checkNewPhone",
			method = RequestMethod.POST,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp checkNewPhone(String newPhone,String code,int userType,Long shopId) throws Exception {
		log.debug("手机号修改（输入新手机号 验证码验证）");
         User user=userDao.findOne(shopId);
        User user1=userDao.findOneByPhone(newPhone);
        if(user1!=null){
          return  JsonResp.fa("此手机号已注册,无法更改！");
        }
		Boolean aBoolean = SmsUtils.checkCode(newPhone, code, userType);
		if(aBoolean){//校验验证码
			user.setPhone(newPhone);
            userDao.save(user);
			return JsonResp.ok();
		}else {
			return JsonResp.fa("验证码错误！");
		}
	}
    /**
     * @返回 商家认证状态
     *
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findShopIsRegisterStatus",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findShopIsRegisterStatus(Long userId) throws Exception {
        log.debug("返回 商家认证状态");
		   User user=userDao.findOne(userId);
            Map map =new HashMap();
            map.put("isRegister",user.getIsRegister());
            return  JsonResp.ok(map);
    }

	/**
	 * @骑手抢单
	 *
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/getOrderWithRide",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp getOrderWithRide(Long orderId,Long rideId) throws JSONException {
		log.debug("骑手抢单");
		User ride= userDao.findOne(rideId);
		Order order = orderDao.findOne(orderId);
		User shop=order.getShop();
		//开始加锁
        Account account =accountDao.findByUser(ride);
		Double goodsMoney=order.getGoodsMoney();//货价
//		Double  takeMoney=order.getTakeMoney();//代收货款
     //   BigDecimal totalMoney=new BigDecimal(goodsMoney).add(new BigDecimal(takeMoney));
            if(goodsMoney.compareTo(account.getDepositMoney())>0 || account.getDepositMoney().compareTo(200D)<0){
                return JsonResp.fa("押金不足无法抢单！");
            }else {
				synchronized (this){
				if (order.getOrderStatus() == 1) {//如果订单状态为待抢单
					order.setRide(ride);
					String distance = orderService.findDistance(orderId);
					order.setDistance(distance);
					order.setOrderStatus(2);//更改为待取货
					order.setRobDatetime(new Date());//骑手抢单时间
					Long s = System.currentTimeMillis() + (order.getLimitTime() + Integer.valueOf(shop.getShopStartTime())) * 60 * 1000;
					String sendTimeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(s);
					try {
						order.setSendTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sendTimeStr));//保存规定送达时间
						orderDao.save(order);
					} catch (ParseException e) {
						e.printStackTrace();
						log.debug("时间转换出错！");
					}
					//从押金中扣除货物价格
					account.setDepositMoney(new BigDecimal(account.getDepositMoney()).subtract(new BigDecimal(goodsMoney)).doubleValue());
					account.setBlockDepositMoney(new BigDecimal(account.getBlockDepositMoney()).add(new BigDecimal(goodsMoney)).doubleValue());
					accountDao.save(account);
					/****************************账户资金流水明细（扣除押金） 骑手*****************************/
					CashRecord cashRecord = new CashRecord();
					cashRecord.setUser(ride);
					cashRecord.setTitle("配送订单冻结金额" + goodsMoney + "元");
					cashRecord.setOrderType(1);//配送订单
					cashRecord.setOrderNumber(order.getOrderNumber());
					cashRecord.setRecoedType(3);//配送订单得钱
					cashRecord.setMoneyType(2);
					cashRecord.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
					cashRecord.setMoney(-goodsMoney);
					cashRecord.setStatus(1);//成功
					cashRecord.setGivePerson(2);
					cashRecord.setReceivePerson(2);
					cashRecordDao.save(cashRecord);
					String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
	/*			//激光推送 发送抢单成功消息至骑手
				List<String> aliasList=new ArrayList<>();
				aliasList.add(ride.getAlias());
				String msg_content="您于"+time+"成功抢到一条订单，请尽快前往提货地点提取。";
				JSONObject jsonObject=new JSONObject();
				jsonObject.put("type",1);
				jsonObject.put("id",order.getId());
				int n=JpushClientUtil.sendToAliasId(aliasList,"抢单通知","抢单成功",msg_content,jsonObject.toString());*/
					//激光推送 发送抢单成功消息至商家
					List<String> aliasListShop = new ArrayList<>();
					aliasListShop.add(order.getShop().getAlias());
					String msg_content2 = "骑手于" + time + "成功抢到一条订单，请保持电话畅通。";
					JSONObject jsonObject2 = new JSONObject();
					jsonObject2.put("type", 1);
					jsonObject2.put("id", order.getId());
					int m = JpushShopClientUtil.sendToAliasId(aliasListShop, "抢单通知", "抢单成功", msg_content2, jsonObject2.toString());
					log.debug("推送状态" + m);
					//短信推送用户
					String phone = order.getAddressUser().getPhone();
					JSONArray phones = new JSONArray();
					phones.put(phone);
					String templateid = "3060370";//抢单成功
					if (phone != null) {
						try {
							SmsUtils.sendMsg(phones, templateid, null, 2);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				} else {
					return JsonResp.fa("该订单已被抢单,或者此订单存在异常!");
				}
			}
        }
		return JsonResp.ok("抢单成功");
	}


	/**
	 * @身份验证、提交审核（商家）
	 * @param jsonObjects
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/checkShopIdentity",
			method = RequestMethod.POST,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp checkShopIdentity(@RequestBody JSONObject jsonObjects) throws Exception {
		log.debug("身份验证、提交审核（商家）");
		//保存地址
		Map<String,String> map = (Map)jsonObjects.get("address");
		Map<String,String> shopMap = (Map)jsonObjects.get("shop");
		User shop=userDao.findOne(Long.parseLong(shopMap.get("shopId")));
		Address address=new Address();
		address.setRealName(shopMap.get("nickName"));
		address.setProvince(map.get("province"));
		address.setCity(map.get("city"));
		address.setCounty(map.get("county"));
		address.setAddressDetail(map.get("addressDetail"));
		address.setLat(map.get("lat"));
		address.setLng(map.get("lng"));
		address.setPhone(shop.getPhone());
		address.setAreaCode(map.get("areaCode"));
        if(map.get("areaCode")==null){
            return JsonResp.fa("区域代码为空，申请认证失败");
        }
		address.setType(2);
		address.setLevel(0);
		address.setStatus(1);
		addressDao.save(address);
		//保存商家资料
		shop.setNickName(shopMap.get("nickName"));
		shop.setRealName(shopMap.get("realName"));
		shop.setIdCard(shopMap.get("idCard"));
		shop.setLicenseUrl(shopMap.get("licenseUrl"));//手持相片自拍照(骑手)/经营许可证(商家可选)
        if("".equals(shopMap.get("licenseUrl")) || shopMap.get("licenseUrl")==null){
            shop.setLicenseUrlStatus(0);
            log.debug("经营许可证状态"+0);
        }else {
            shop.setLicenseUrlStatus(1);
            log.debug("经营许可证状态"+1);
        }
		shop.setIdentityFront(shopMap.get("identityFront"));//身份证正面(骑-商)
		shop.setIdentityBack(shopMap.get("shopImg"));//营业执照
		String s=shopMap.get("storeUrl");
		shop.setStoreUrl(s);//商家店面照
		shop.setAddress(address.getId());
		shop.setIsRegister(2);
		shop.setUserStatus(1);
        shop.setUserType(3);
		shop.setVoice(1);
        shop.setServeType(1);//服务状态 1正常 2处罚
		shop.setShopStartMoney(0.00);
		userDao.save(shop);
		//店铺类型
		Map<String,String> shopTypeMap = (HashMap)jsonObjects.get("shopType");
		String type = shopTypeMap.get("type");
		String[] types  = type.split("\\*\\*\\*");
		List<SortBetween> sortBetweenList=new ArrayList<>();
		for (String str:types) {
			SortBetween sortBetween = new SortBetween();
			SortType st=sortTypeDao.findOne(Long.valueOf(str));
			sortBetween.setShop(shop);
			sortBetween.setType(1);
			sortBetween.setSortTypeId(st);
			sortBetweenList.add(sortBetween);
		}
		sortBetweenDao.save(sortBetweenList);
		//返回认证中状态
		Map<String,Object> resultMap =new HashMap();
		resultMap.put("isRegister",shop.getIsRegister());
		return JsonResp.ok(resultMap);
	}


	/**
	 * @身份验证、提交审核（骑手）
	 * @param jsonObjects
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/checkIdentity",
			method = RequestMethod.POST,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp checkIdentity(@RequestBody JSONObject jsonObjects) throws Exception {
		log.debug("身份验证、提交审核（骑手）");
		//保存地址
		Map<String,String> map = (HashMap)jsonObjects.get("address");
		Map<String,String> rideMap = (HashMap)jsonObjects.get("ride");
		User ride=userDao.findOne(Long.parseLong(rideMap.get("rideId")));
		Address address=new Address();
		address.setRealName(rideMap.get("realName"));
		address.setProvince(map.get("province"));
		address.setCity(map.get("city"));
		address.setCounty(map.get("county"));
		address.setLat(map.get("lat"));
		address.setLng(map.get("lng"));
		address.setAreaCode(map.get("areaCode"));
		address.setPhone(ride.getPhone());
		address.setLevel(0);
		address.setStatus(1);
		address.setType(4);
		addressDao.save(address);
        //保存骑手资料
        ride.setRealName(rideMap.get("realName"));
        ride.setIdCard(rideMap.get("idCard"));
        ride.setLicenseUrl(rideMap.get("licenseUrl"));
        ride.setIdentityFront(rideMap.get("identityFront"));
        ride.setIsWork(0);//默认不工作
        ride.setHealthCard(rideMap.get("healthCard"));
        if(rideMap.get("healthCard")==null || "".equals(rideMap.get("healthCard")) || "null".equals(rideMap.get("healthCard"))){
            ride.setHealthCardStatus(0);
        }else {
            ride.setHealthCardStatus(1);
        }
        log.debug("有没有上传健康证healthCard="+rideMap.get("healthCard"));
        ride.setAddress(address.getId());
		ride.setIsRegister(2);//认证中
		ride.setUserStatus(1);
		ride.setVoice(1);
        ride.setServeType(1);//服务状态 1正常 2处罚
		ride.setOrderTicket(0.00);//每单罚款金额
        userDao.save(ride);
		return JsonResp.ok();
	}

    /**
     * @骑手抢单页面数据（今日收入、本月收入、今日抢单数量等）
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/getRideOneDayMoney",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp getRideOneDayMoney(Long rideId,String lat,String lng) throws Exception {
        log.debug("骑手抢单页面数据（今日收入、本月收入、今日抢单数量等）");
        User user = userDao.findOne(rideId);
        // 定义一个map集合保存数据
        Map map = new HashMap();
        if(user==null || user.getIsRegister()!=1){//如果没有有认证通过
            map.put("currentDayMoney", 0);
            map.put("currentMonthMoney",0);
            map.put("currentDayOrderNum", 0);
            map.put("isWork", 0);
            map.put("isRegister", user==null?0:user.getIsRegister());
			map.put("produceOrderSize", 0);
        }else {
            List<Order> orderList = orderDao.findByRide(user);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //  List<Order> currentDaySendOrderList=new ArrayList<>();//当天送达的订单集合
            List<Order> currentDayRobOrderList = new ArrayList<>();//当天抢单集合
            // List<Order> currentMonthSendOrderList=new ArrayList<>();//当月送达的订单集合
            List<String> currentMonthSendOrderNumberList = new ArrayList<>();//当月送达的订单编码集合
            List<String> currentDaySendOrderNumberList = new ArrayList<>();//当天送达的订单编码集合
            for (int i = 0, y = orderList.size(); i < y; i++) {
                Order order = orderList.get(i);
				DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				Date rob_datetime = order.getRobDatetime();//接单日期
				String robDateStr = rob_datetime.toString().substring(0, 10);//接单日期
				String todayDateStr = sdf.format(new Date());//当日日期
				Date todayDate = df.parse(todayDateStr);
				Date robDate = df.parse(robDateStr);
                if(order.getSendDatetime() != null){
                    Date send_datetime = order.getSendDatetime();//送达时间
                    String sendDateStr = send_datetime.toString().substring(0, 10);//送达日期
                    String oldStr = todayDateStr.substring(0, 7);//截取掉“-dd”保留“yyyy-MM”
                    String newStr = "-01";
                    String currentMonthDateStr = oldStr + newStr;//当月的第一日
                    Date sendDate = df.parse(sendDateStr);
                    Date currentMonthDate = df.parse(currentMonthDateStr);
                    if (sendDate.compareTo(todayDate)==0) { //判断两个日期是否一样
                        // currentDaySendOrderList.add(order);
                        currentDaySendOrderNumberList.add(order.getOrderNumber());
                    }
                    //如果送达日期在当月之中
                    if (sendDate.compareTo(currentMonthDate)>=0 && sendDate.compareTo(todayDate)<=0) {
                        //currentMonthSendOrderList.add(order);
                        currentMonthSendOrderNumberList.add(order.getOrderNumber());
                    }
                }
				if (robDate.compareTo(todayDate)==0) { //如果接单日期和当天一样
					currentDayRobOrderList.add(order);
				}
            }
            //判断当前时间是否在工作时间内 有没有请假
            Boolean isWorkDate=false;
            DateFormat time = new SimpleDateFormat("HH:mm:ss");
            String currentTimeStr = time.format(new Date());
            Date currentTime = time.parse(currentTimeStr); //当前时间
            List<Date> dateList=new ArrayList<>();
            Date today=new SimpleDateFormat("yyyy-MM-dd").parse(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            dateList.add(today);
            List<UserLeave> userLeaveList=userLeaveDao.findByLeaveDateInAndUser(dateList,user);
            if(userLeaveList.isEmpty()){//没有请假
                if(user.getFullTime()==1){//如果全职
                    int isMorning=user.getIsMorning()==null?1:user.getIsMorning();
                    if(isMorning==1){//如果是早班
                        String workTimeArr[]=user.getWorktimeMon().split(",");
                        for(int i=0;i<workTimeArr.length;i++){
                            String tiemArr[]=workTimeArr[i].trim().split("-");
                            for(int y=0;y<tiemArr.length;y++){
                                Date startWorkTime = time.parse(tiemArr[0]);//获取开始工作时间
                                Date endWorkTime = time.parse(tiemArr[1]);//获取结束工作时间
                                if(currentTime.getTime() >= startWorkTime.getTime() && currentTime.getTime() <= endWorkTime.getTime()){
                                    isWorkDate=true;
                                    break;
                                }
                            }
                        }
                    }else if(isMorning==2){//晚班
                        String workTimeArr[]=user.getWorktimeEve().split(",");
                        for(int i=0;i<workTimeArr.length;i++){
                            String tiemArr[]=workTimeArr[i].trim().split("-");
                            for(int y=0;y<tiemArr.length;y++){
                                Date startWorkTime = time.parse(tiemArr[0]);//获取开始工作时间
                                Date endWorkTime = time.parse(tiemArr[1]);//获取结束工作时间
                                if(currentTime.getTime() >= startWorkTime.getTime() && currentTime.getTime() <= endWorkTime.getTime()){
                                    isWorkDate=true;
                                    break;
                                }
                            }
                        }
                    }
                }else if(user.getFullTime()==2){
                    isWorkDate=false;
                }

            }

            //如果没有手动启动工作 当前时间在工作时间范围内且是全职  则自动启动工作
            if (user.getIsWork() == 0 && isWorkDate ) {
                user.setIsWork(1);
                userDao.save(user);
            }
            //计算当天收入
            List<CashRecord> cashRecordList = cashRecordDao.findByOrderNumberIn(currentDaySendOrderNumberList);
            Double currentDayTotalMoney = 0.00;
            for (int i = 0, y = cashRecordList.size(); i < y; i++){
                CashRecord cashRecord = cashRecordList.get(i);
                if(user==cashRecord.getUser() && cashRecord.getRecoedType()==4 && cashRecord.getMoneyType()==1)
                {//判断该条交易记录是否是该骑手的记录单子
                    Double money = cashRecord.getMoney();
                    BigDecimal b1 = new BigDecimal(String.valueOf(money));
                    BigDecimal b2 = new BigDecimal(String.valueOf(currentDayTotalMoney));
                    currentDayTotalMoney = b1.add(b2).doubleValue();
                }
            }
            //计算当月收入
            List<CashRecord> cashRecordMonthList = cashRecordDao.findByOrderNumberIn(currentMonthSendOrderNumberList);
            Double currentMonthTotalMoney = 0.00;
            for (int i = 0, y = cashRecordMonthList.size(); i < y; i++) {
                CashRecord cashRecord = cashRecordMonthList.get(i);
                if(user==cashRecord.getUser() && cashRecord.getRecoedType()==4 && cashRecord.getMoneyType()==1){//判断该条交易记录是否是该骑手的记录单子
                    Double money = cashRecord.getMoney();
                    BigDecimal b1 = new BigDecimal(String.valueOf(money));
                    BigDecimal b2 = new BigDecimal(String.valueOf(currentMonthTotalMoney));
                    currentMonthTotalMoney = b1.add(b2).doubleValue();
                }

            }

            //计算三公里以内产生的订单数量
			String sql= "SELECT \n" +
					"  a.id,\n" +
					"  FORMAT(6378.138 * 2 * ASIN(SQRT(POW(SIN(\n" +
					"    (\n" +lat+"*PI()/180-b.lat*PI()/180)/2),2)+\n" +
					"      COS(\n" +lat+"*PI()/180)*COS(b.lat*PI()/180)*POW(SIN(("+lng+"*PI()/180-b.lng*PI()/180)/2),2)\n" +
					"      )\n" +
					"    ),\n" +
					"    2\n" +
					"  ) AS distance FROM address b,user a\n"+
					" where a.address=b.id and b.status=1 and b.type=2";
			Query query = entityManager.createNativeQuery(sql);
			entityManager.close();
			query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
			List<Map> mapList = new ArrayList<>();
			query.getResultList().forEach(n -> mapList.add(PubLib.copyObject(PubLib.convert(n), Map.class)));
			List<Long> idList=new ArrayList<>();
			for(Map map2:mapList){
				if(Double.valueOf(String.valueOf(map2.get("distance"))).compareTo(Double.valueOf(3))<=0){
					idList.add(Long.valueOf(String.valueOf(map2.get("id"))));
				}
			}
			List<User> userList=userDao.findByIdIn(idList);
			List<Order> produceOrderList=orderDao.findByShopInAndOrderStatus(userList,1);
            map.put("currentDayMoney", currentDayTotalMoney);
            map.put("currentMonthMoney", currentMonthTotalMoney);
            map.put("currentDayOrderNum", currentDayRobOrderList.size());
            map.put("isWork", user.getIsWork());
            map.put("isRegister", user.getIsRegister());
			map.put("produceOrderSize", produceOrderList.size());
        }
        return JsonResp.ok(map);
    }


	/**
	 * @骑手今日收入、今日抢单数量(地图使用)
	 * @param
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/getRideOneDayUseByMap",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp getRideOneDayUseByMap(Long rideId) throws Exception {
		log.debug("骑手今日收入、今日抢单数量(地图使用)");
		User user = userDao.findOne(rideId);
		// 定义一个map集合保存数据
		Map map = new HashMap();
		if(user.getIsRegister()!=1){//如果没有有认证通过
			map.put("currentDayMoney", 0);
			map.put("currentMonthMoney",0);
			map.put("currentDayOrderNum", 0);
			map.put("isWork", 0);
			map.put("isRegister", user.getIsRegister());
			map.put("produceOrderSize", 0);
		}else {
			List<Order> orderList = orderDao.findByRide(user);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			//  List<Order> currentDaySendOrderList=new ArrayList<>();//当天送达的订单集合
			List<Order> currentDayRobOrderList = new ArrayList<>();//当天抢单集合
			// List<Order> currentMonthSendOrderList=new ArrayList<>();//当月送达的订单集合
			List<String> currentMonthSendOrderNumberList = new ArrayList<>();//当月送达的订单编码集合
			List<String> currentDaySendOrderNumberList = new ArrayList<>();//当天送达的订单编码集合
			for (int i = 0, y = orderList.size(); i < y; i++) {
				Order order = orderList.get(i);
				DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				Date rob_datetime = order.getRobDatetime();//接单日期
				String robDateStr = rob_datetime.toString().substring(0, 10);//接单日期
				String todayDateStr = sdf.format(new Date());//当日日期
				Date todayDate = df.parse(todayDateStr);
				Date robDate = df.parse(robDateStr);
				if(order.getSendDatetime() != null){
					Date send_datetime = order.getSendDatetime();//送达时间
					String sendDateStr = send_datetime.toString().substring(0, 10);//送达日期
					String oldStr = todayDateStr.substring(0, 7);//截取掉“-dd”保留“yyyy-MM”
					String newStr = "-01";
					String currentMonthDateStr = oldStr + newStr;//当月的第一日
					Date sendDate = df.parse(sendDateStr);
					Date currentMonthDate = df.parse(currentMonthDateStr);
					if (sendDate.compareTo(todayDate)==0) { //判断两个日期是否一样
						// currentDaySendOrderList.add(order);
						currentDaySendOrderNumberList.add(order.getOrderNumber());
					}
					//如果送达日期在当月之中
					if (sendDate.compareTo(currentMonthDate)>=0 && sendDate.compareTo(todayDate)<=0) {
						//currentMonthSendOrderList.add(order);
						currentMonthSendOrderNumberList.add(order.getOrderNumber());
					}
				}
				if (robDate.compareTo(todayDate)==0) { //如果接单日期和当天一样
					currentDayRobOrderList.add(order);
				}
			}
			//判断当前时间是否在工作时间内 有没有请假
			Boolean isWorkDate=false;
			DateFormat time = new SimpleDateFormat("HH:mm:ss");
			String currentTimeStr = time.format(new Date());
			Date currentTime = time.parse(currentTimeStr); //当前时间
			List<Date> dateList=new ArrayList<>();
			Date today=new SimpleDateFormat("yyyy-MM-dd").parse(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
			dateList.add(today);
			List<UserLeave> userLeaveList=userLeaveDao.findByLeaveDateInAndUser(dateList,user);
			if(userLeaveList.isEmpty()){//没有请假
				if(user.getFullTime()==1){//如果全职
					if(user.getIsMorning()==1){//如果是早班
						String workTimeArr[]=user.getWorktimeMon().split(",");
						for(int i=0;i<workTimeArr.length;i++){
							String tiemArr[]=workTimeArr[i].trim().split("-");
							for(int y=0;y<tiemArr.length;y++){
								Date startWorkTime = time.parse(tiemArr[0]);//获取开始工作时间
								Date endWorkTime = time.parse(tiemArr[1]);//获取结束工作时间
								if(currentTime.getTime() >= startWorkTime.getTime() && currentTime.getTime() <= endWorkTime.getTime()){
									isWorkDate=true;
									break;
								}
							}
						}
					}else if(user.getIsMorning()==2){//晚班
						String workTimeArr[]=user.getWorktimeEve().split(",");
						for(int i=0;i<workTimeArr.length;i++){
							String tiemArr[]=workTimeArr[i].trim().split("-");
							for(int y=0;y<tiemArr.length;y++){
								Date startWorkTime = time.parse(tiemArr[0]);//获取开始工作时间
								Date endWorkTime = time.parse(tiemArr[1]);//获取结束工作时间
								if(currentTime.getTime() >= startWorkTime.getTime() && currentTime.getTime() <= endWorkTime.getTime()){
									isWorkDate=true;
									break;
								}
							}
						}
					}
				}else if(user.getFullTime()==2){
					isWorkDate=false;
				}

			}

			//如果没有手动启动工作 当前时间在工作时间范围内且是全职  则自动启动工作
			if (user.getIsWork() == 0 && isWorkDate && user.getFullTime()==1) {
				user.setIsWork(1);
				userDao.save(user);
			}
			//计算当天收入
			List<CashRecord> cashRecordList = cashRecordDao.findByOrderNumberIn(currentDaySendOrderNumberList);
			Double currentDayTotalMoney = 0.00;
			for (int i = 0, y = cashRecordList.size(); i < y; i++){
				CashRecord cashRecord = cashRecordList.get(i);
				if(user==cashRecord.getUser() && cashRecord.getRecoedType()==4 && cashRecord.getMoneyType()==1)
				{//判断该条交易记录是否是该骑手的记录单子
					Double money = cashRecord.getMoney();
					BigDecimal b1 = new BigDecimal(money.toString());
					BigDecimal b2 = new BigDecimal(currentDayTotalMoney.toString());
					currentDayTotalMoney = b1.add(b2).doubleValue();
				}
			}
			//计算当月收入
			List<CashRecord> cashRecordMonthList = cashRecordDao.findByOrderNumberIn(currentMonthSendOrderNumberList);
			Double currentMonthTotalMoney = 0.00;
			for (int i = 0, y = cashRecordMonthList.size(); i < y; i++) {
				CashRecord cashRecord = cashRecordMonthList.get(i);
				if(user==cashRecord.getUser() && cashRecord.getRecoedType()==4 && cashRecord.getMoneyType()==1){//判断该条交易记录是否是该骑手的记录单子
					Double money = cashRecord.getMoney();
					BigDecimal b1 = new BigDecimal(money.toString());
					BigDecimal b2 = new BigDecimal(currentMonthTotalMoney.toString());
					currentMonthTotalMoney = b1.add(b2).doubleValue();
				}

			}
			map.put("currentDayMoney", currentDayTotalMoney);
			map.put("currentMonthMoney", currentMonthTotalMoney);
			map.put("currentDayOrderNum", currentDayRobOrderList.size());
			map.put("isWork", user.getIsWork());
			map.put("isRegister", user.getIsRegister());


		}
		return JsonResp.ok(map);
	}

	/**
	 * @return 返回值JsonResp
	 * @骑手当前订单
	 */
	@RequestMapping(value = "/riderCurrentOrders",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp riderCurrentOrders(Long rideId) {
		log.debug("骑手当前订单");
		String sql=" SELECT * FROM orders where order_status in(2,3) and ride="+rideId +" ";
		List resultList = (List)sqlToResult.getResultList(sql);
		List<Map> maps=new ArrayList<>();
		for (Object o : resultList) {
			Map map=PubLib.copyObject(o, Map.class);
			maps.add(map);
		}
		return JsonResp.ok(maps);
	}

    /**
     * @return 骑手点击出货异常调用方发
     * @骑手当前订单
     */
    @RequestMapping(value = "/applyOrderException",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp applyOrderException(Long orderId) {
        log.debug("骑手点击出货异常调用方发");
         Order order=orderDao.findOne(orderId);
        Long orderTime=System.currentTimeMillis()-order.getRobDatetime().getTime(); //当前时间和骑手抢单时间差
        User shop=order.getShop();
        Long shopStartTime=Long.valueOf(Integer.parseInt(shop.getShopStartTime())*60*1000)+5*60*1000;
        if(orderTime.compareTo(shopStartTime)<0){
            return JsonResp.fa("当前时间不能上报出货异常");
        }
        return JsonResp.ok("可以上报",200);
    }




	/**
	 * @设置工作时间(骑手)
	 *
	 * @return 返回值JsonResp
	 */
/*	@RequestMapping(value = "/siteWorkTime",
			method = RequestMethod.POST,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp siteWorkTime(String workTime,String workDate) throws Exception {
		log.debug("设置工作时间(骑手)");
		JsonResp jsonResp = userService.findLoginUser();
		Long ride = userService.currentUserId();
		User user = userDao.findOne(ride);
		user.setWorkDate(workDate);
		user.setWorkTime(workTime);
		userDao.save(user);
		return JsonResp.ok();
	}*/


	/**
	 * @上报货物损坏（骑手）
	 *
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/goodsDamage",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp goodsDamage(Long orderId,Long rideId) throws JSONException {
		log.debug("上报货物损坏（骑手）");
		User ride = userDao.findOne(rideId);
		Order order = orderDao.findOne(orderId);
		User shop = order.getShop();
		Double sendMoney = order.getSendMoney();//配送费
		Double tip = order.getOrderTip();//订单小费
		Double takeMoney = order.getTakeMoney();//代收货款
		Double changeMoney=order.getChangeMoney();//变更费
		Double goodsMoney=order.getGoodsMoney();//货物价格
		//流动总资金
		BigDecimal fTotalMoney=new BigDecimal(String.valueOf(sendMoney)).add(new BigDecimal(String.valueOf(tip))).add(new BigDecimal(String.valueOf(changeMoney)));
		if (order.getRide().equals(ride)) {
            if(order.getIsGoodsBad()==0){
                Account accountRide = accountDao.findByUser(ride);
                Account accountShop = accountDao.findByUser(shop);
                //从商家冻结余额中减去订单总支付
                accountShop.setBlockMoney(new BigDecimal(accountShop.getBlockMoney()).subtract(fTotalMoney).doubleValue());
                accountShop.setAllMoney(new BigDecimal(accountShop.getAllMoney()).add(fTotalMoney).add(new BigDecimal(goodsMoney)).doubleValue());
                //从骑手冻结押金中减去货物价格
                accountRide.setBlockDepositMoney(new BigDecimal(accountRide.getBlockDepositMoney()).subtract(new BigDecimal(goodsMoney)).doubleValue());
                accountDao.save(accountRide);
                accountDao.save(accountShop);
                order.setIsGoodsBad(1);//更改为货物损坏
                order.setOrderStatus(6);//更改为货物损坏
                order.setSendDatetime(new Date());//记录货物损坏时间
                orderDao.save(order);
                /*****************记录账户明细(支付金额返回余额) 商家**********************/
                CashRecord cashRecordShop=new CashRecord();
                cashRecordShop.setUser(shop);
                cashRecordShop.setTitle("配送订单损坏返还配送费"+fTotalMoney+"元");
                cashRecordShop.setOrderType(1);//配送订单
                cashRecordShop.setOrderNumber(order.getOrderNumber());
                cashRecordShop.setRecoedType(4);//配送订单得钱
                cashRecordShop.setMoneyType(1);
                cashRecordShop.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                cashRecordShop.setMoney(fTotalMoney.doubleValue());
                cashRecordShop.setStatus(1);//成功
				cashRecordShop.setReceivePerson(1);
				cashRecordShop.setGivePerson(1);
                cashRecordDao.save(cashRecordShop);
				/*****************记录账户明细(骑手赔偿货价) 商家**********************/
				CashRecord cashRecordShop2=new CashRecord();
				cashRecordShop2.setUser(shop);
				cashRecordShop2.setTitle("配送订单损坏赔付货款金额"+goodsMoney+"元");
				cashRecordShop2.setOrderType(1);//配送订单
				cashRecordShop2.setOrderNumber(order.getOrderNumber());
				cashRecordShop2.setRecoedType(4);//配送订单得钱
				cashRecordShop2.setMoneyType(1);
				cashRecordShop2.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
				cashRecordShop2.setMoney(goodsMoney);
				cashRecordShop2.setStatus(1);//成功
				cashRecordShop2.setGivePerson(2);
				cashRecordShop2.setReceivePerson(1);
				cashRecordDao.save(cashRecordShop2);
                /*****************记录账户明细 骑手**********************/
                CashRecord cashRecordRide=new CashRecord();
                cashRecordRide.setUser(ride);
                cashRecordRide.setTitle("配送订单损坏赔付货款金额"+goodsMoney+"元");
                cashRecordRide.setOrderType(1);//配送订单
                cashRecordRide.setOrderNumber(order.getOrderNumber());
                cashRecordRide.setRecoedType(3);//货价赔钱
                cashRecordRide.setMoneyType(2);
                cashRecordRide.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                cashRecordRide.setMoney(-goodsMoney);
                cashRecordRide.setStatus(1);//成功
				cashRecordRide.setGivePerson(2);
				cashRecordRide.setReceivePerson(1);
                cashRecordDao.save(cashRecordRide);
				/*****************记录账户明细 骑手**********************/
				CashRecord cashRecordRide2=new CashRecord();
				cashRecordRide2.setUser(ride);
				cashRecordRide2.setTitle("配送订单解冻金额"+goodsMoney+"元");
				cashRecordRide2.setOrderType(1);//配送订单
				cashRecordRide2.setOrderNumber(order.getOrderNumber());
				cashRecordRide2.setRecoedType(4);//得钱
				cashRecordRide2.setMoneyType(2);
				cashRecordRide2.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
				cashRecordRide2.setMoney(goodsMoney);
				cashRecordRide2.setStatus(1);//成功
				cashRecordRide2.setGivePerson(1);
				cashRecordRide2.setReceivePerson(2);
				cashRecordDao.save(cashRecordRide2);
				//激光推送
				List<String> aliasList=new ArrayList<>();
				aliasList.add(shop.getAlias());
				String msg_content="您有订单在配送中损坏";
				JSONObject jsonObject2=new JSONObject();
				jsonObject2.put("type",4);
				jsonObject2.put("id",order.getId());
			
				int n=JpushShopClientUtil.sendToAliasId(aliasList,"货物损坏通知","货物损坏",msg_content,jsonObject2.toString());
				System.out.print("骑手上报货物损坏通知，消息推送状态n="+n);
                //短信推送用户
                String phone=order.getAddressUser().getPhone();
				JSONArray phones=new JSONArray();
				phones.put(phone);
                String templateid ="3057410";//货物损坏
                if(phone!=null){
                    try {
                        SmsUtils.sendMsg(phones,templateid,null,2);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
				return JsonResp.ok();
            }else {
                return  JsonResp.fa("该订单已经上报过货物损坏");
            }


		} else {
			return JsonResp.fa("身份验证错误!");
		}

	}

	/**
	 * @设置(骑手)
	 *
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/findSitePageDate",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp findSitePageDate(Long userId) throws Exception {
		log.debug("设置工作时间(骑手)");
		Map map=new HashMap();
		User user=userDao.findOne(userId);
        int userType=user.getUserType();
        int isRegister=user.getIsRegister();
        if(isRegister==0){
            map.put("licenseUrl",null);
            map.put("shopStartTime",null);
            map.put("phone",user.getPhone());
            map.put("voice",null);
            map.put("healthCard",null);//健康证
            map.put("licenseUrlStatus",0);//经营许可证（商家）0代表未上传1代表审核中2代表审核通过3代表审核失败
            map.put("healthCardStatus",0);//健康证状态（骑手）0代表未上传1代表审核中2代表审核通过3代表审核失败
            map.put("workTimeList",null);
        }
		List<UserLeave> userLeaveList=userLeaveDao.findByApprove(1);
		List<Date> dateList =new ArrayList<>();//请假日期
        for (UserLeave u:userLeaveList ) {
            dateList.add(u.getLeaveDate());
        }
        if(dateList.size()==0){
			map.put("isLeaveDate","无");
		}else {
			map.put("isLeaveDate",dateList);
		}
		String workTimeArr[]=null;
		if(userType==2){
			if(user.getFullTime()==1 ){//全职
				if(user.getIsMorning()==1){
					workTimeArr=user.getWorktimeMon().split(",");
				}else if(user.getIsMorning()==2){
					workTimeArr=user.getWorktimeEve().split(",");
				}
			}
		}
		map.put("licenseUrl",user.getLicenseUrl());
		map.put("shopStartTime",user.getShopStartTime());
		map.put("phone",user.getPhone());
		map.put("voice",user.getVoice());
		map.put("healthCard",user.getHeadUrl());//健康证
        map.put("licenseUrlStatus",user.getLicenseUrlStatus());//经营许可证（商家）0代表未上传1代表审核中2代表审核通过3代表审核失败
        map.put("healthCardStatus",user.getHealthCardStatus());//健康证状态（骑手）0代表未上传1代表审核中2代表审核通过3代表审核失败
		if(workTimeArr!=null){
			map.put("workTimeList",Arrays.asList(workTimeArr));
		}else {
			map.put("workTimeList",workTimeArr);
		}
		return  JsonResp.ok(map);
	}



	/**
	 * 分页查询(jpa方式)
	 * @param user 分页条件
	 * @param pageNum 第几页
	 * @param pageSize 每页的条数
	 * @return JsonResp
	 */
	@RequestMapping(value = "/jpa/page",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp findPageUserJpa(User user, Integer pageNum,Integer pageSize) {
		log.debug("分页查询(jpa方式)");
		//多条件排序Sort
		//Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
		//排序Sort
		Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
		Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
		Page page;
		if (null == user) {
			page = userDao.findAll(pageable); //无条件分页
		}else{
			final String phone =  user.getPhone();
			page = userDao.findAll( 		  //条件分页
					(root, criteriaQuery, cb) -> {
						Predicate predicate = cb.conjunction();
						List<Expression<Boolean>> expressions = predicate.getExpressions();
						if (StringUtils.isNotBlank(phone)) {
							expressions.add(cb.like(root.<String>get("phone"), "%"+ phone +"%"));
						}
						return predicate;
					}, pageable);
		}
//        List<User> content = page.getContent();
//        for (User user1 : content) {
//        }
		return JsonResp.ok(new PageDto(page));
	}

	/**
	 * 分页查询审核证书列表(jpa方式)
	 * @param pageNum 第几页
	 * @param pageSize 每页的条数
	 * @return JsonResp
	 */
	@RequestMapping(value = "/jpa/cardPage",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp findCardPagea(Integer userType, Integer pageNum,Integer pageSize) {
		log.debug("分页查询审核证书列表(jpa方式)");
		//多条件排序Sort
		//Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
		//排序Sort
		Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
		Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
		Page page;
			page = userDao.findAll( 		  //条件分页
					(root, criteriaQuery, cb) -> {
						Predicate predicate = cb.conjunction();
						List<Expression<Boolean>> expressions = predicate.getExpressions();
						if (userType==2) {
							expressions.add(cb.equal(root.get("healthCardStatus"), 1));
						}else{
							expressions.add(cb.equal(root.get("licenseUrlStatus"), 1));
						}
						return predicate;
					}, pageable);
//        List<User> content = page.getContent();
//        for (User user1 : content) {
//        }
		return JsonResp.ok(new PageDto(page));
	}

	/**
	 * @设置审核通过
	 *
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/setPass",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp setPass(Long userId,String worktimeMon,String worktimeEve,Integer changeDays,Integer restDays,Integer dailyTasks,Double orderTicket,Double fulltimeRate) throws Exception {
		log.debug("设置审核通过");
		User user=userDao.findOne(userId);
		//判断该骑手注册地区是否已开通
		Address address = addressDao.findOne(user.getAddress());
		OpenArea openArea = openAreaDao.findByAreaCode(address.getAreaCode());
		if (openArea==null||openArea.equals("")){
			return JsonResp.fa("用户注册地区未开通！");
		}else if("".equals(address.getLat()) || "".equals(address.getLng())){
			return JsonResp.fa("该用户注册地址缺失经纬度，审核失败");
		}else if(user.getUserType()==2){
			user.setChangeDays(changeDays);
			user.setWorktimeEve(worktimeEve);
			user.setWorktimeMon(worktimeMon);
			user.setRestDays(restDays);
			user.setDailyTasks(dailyTasks);
			user.setOrderTicket(orderTicket);
			user.setServiceRate(fulltimeRate);
			user.setIsWork(0);
			user.setDailyDeduction(0);
			user.setIsRegister(1);//
			user.setIsMorning(1);
           // user.setHealthCardStatus(1);
			user.setIsTest(2);//没有参加考试
			user.setFullTime(1);
			userDao.save(user);
		}else{
			user.setIsRegister(1);
			userDao.save(user);
		}
		//发送审核通过短信
		String phone =user.getPhone();
		JSONArray phones=new JSONArray();
		phones.put(phone);
		if(user.getUserType()==2){
			SmsUtils.sendMsg(phones,"3056315 ",null,user.getUserType());
		}else{
			SmsUtils.sendMsg(phones,"3049409 ",null,user.getUserType());
		}
		return JsonResp.ok();

	}

	/**
	 * @设置审核失败
	 *
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/setFail",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp setFail(Long userId) throws Exception {
		log.debug("设置审核失败");
		User user=userDao.findOne(userId);
		user.setIsRegister(3);
		userDao.save(user);
		//发送审核通过短信	`
		String phone =user.getPhone();
		JSONArray phones=new JSONArray();
		phones.put(phone);
		if(user.getUserType()==2){
			SmsUtils.sendMsg(phones,"3049407 ",null,user.getUserType());
		}else{
			SmsUtils.sendMsg(phones,"3056316 ",null,user.getUserType());
		}
		return JsonResp.ok();
	}

	/**
	 * @设置上传证件审核成功
	 *
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/setCardPass",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp setCardPass(Long userId,Integer userType) throws Exception {
		log.debug("设置上传证件审核成功");
		User user=userDao.findOne(userId);
		if(userType==2){
			user.setHealthCardStatus(2);
		}else{
			user.setLicenseUrlStatus(2);
		}
		userDao.save(user);
		return JsonResp.ok();
	}

	/**
	 * @设置上传证件审核失败
	 *
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/setCardFail",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp setCardFail(Long userId,Integer userType) throws Exception {
		log.debug("设置上传证件审核失败");
		User user=userDao.findOne(userId);
		if(userType==2){
			user.setHealthCardStatus(3);
		}else{
			user.setLicenseUrlStatus(3);
		}
		userDao.save(user);
		return JsonResp.ok();
	}



	/**
	 * @头像上传
	 *
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/upLoadHeadUrl",
			method = RequestMethod.POST,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp upLoadHeadUrl(Long userId,String headUrl) throws Exception {
		log.debug("设置头像");
		User user=userDao.findOne(userId);
		user.setHeadUrl(headUrl);
		userDao.save(user);
		return JsonResp.ok("上传头像成功");
	}


	/**
	 * @骑手开启或关闭工作时间
	 *
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/openWorkTime",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp openWorkTime(Long rideId,Integer type) throws Exception {
		log.debug("骑手开启或关闭工作时间");
		User user=userDao.findOne(rideId);
		Boolean isWorkDate=false;
		if(user.getFullTime()==1) {//全职
			if (type == 2) {//如果在工作时间内，不能关闭工作
				//判断当前时间是否在工作时间内 有没有请假
				DateFormat time = new SimpleDateFormat("HH:mm:ss");
				String currentTimeStr = time.format(new Date());
				Date currentTime = time.parse(currentTimeStr); //当前时间
				List<Date> dateList = new ArrayList<>();
				Date today = new SimpleDateFormat("yyyy-MM-dd").parse(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
				dateList.add(today);
				List<UserLeave> userLeaveList = userLeaveDao.findByLeaveDateInAndUser(dateList, user);
				if (userLeaveList.isEmpty()) {//没有请假
					if (user.getIsMorning() == 1) {//如果是早班
						String workTimeArr[] = user.getWorktimeMon().split(",");
						for (int i = 0; i < workTimeArr.length; i++) {
							String tiemArr[] = workTimeArr[i].trim().split("-");
							for (int y = 0; y < tiemArr.length; y++) {
								Date startWorkTime = time.parse(tiemArr[0]);//获取开始工作时间
								Date endWorkTime = time.parse(tiemArr[1]);//获取结束工作时间
								if (currentTime.getTime() >= startWorkTime.getTime() && currentTime.getTime() <= endWorkTime.getTime()) {
									isWorkDate = true;
									break;
								}
							}
						}
					} else if (user.getIsMorning() == 2) {//晚班
						String workTimeArr[] = user.getWorktimeEve().split(",");
						for (int i = 0; i < workTimeArr.length; i++) {
							String tiemArr[] = workTimeArr[i].trim().split("-");
							for (int y = 0; y < tiemArr.length; y++) {
								Date startWorkTime = time.parse(tiemArr[0]);//获取开始工作时间
								Date endWorkTime = time.parse(tiemArr[1]);//获取结束工作时间
								if (currentTime.getTime() >= startWorkTime.getTime() && currentTime.getTime() <= endWorkTime.getTime()) {
									isWorkDate = true;
									break;
								}
							}
						}
					}
				}
			}
		}
       if(isWorkDate && type==2){
          return  JsonResp.fa("工作时间内禁止关闭工作状态");
		}else{
		   if(type==2){
			   user.setIsWork(0);
		   }else if(type==1){
			   user.setIsWork(1);
		   }
	   }
		userDao.save(user);
		return JsonResp.ok();
	}

	/**
	 * 新增用户
	 * @param user 用户
	 * @param province 省
	 * @param city 市
	 * @param county 区
	 * @param addressDetail 地址详情
	 * @return JsonResp
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/adduser",
			method = RequestMethod.POST,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp adduser(@RequestBody User user,String province,String city,String county,String addressDetail) throws Exception  {
		log.debug("新增用户");
		//创建地址
		Address a=new Address();
		a.setRealName(user.getRealName());
		a.setPhone(user.getPhone());
		a.setSex(user.getSex());
		a.setProvince(province);
		a.setCity(city);
		a.setCounty(county);
		a.setAddressDetail(addressDetail);
		addressDao.save(a);
		Long id=a.getId();
		user.setAddress(id);
		user.setIsRegister(0);
		user.setUserStatus(1);
		userDao.save(user);
		//创建账户
		Account account=new Account();
		account.setUser(user);
		account.setBlockDepositMoney(0d);
		account.setStatus(1);
		account.setBlockMoney(0d);
		account.setAllMoney(0d);
		account.setDepositMoney(0d);
		accountDao.save(account);
		return JsonResp.ok();
	}

	/**
	 * 编辑用户信息
	 * @param userId 用户
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/updateUser",
			method = RequestMethod.POST,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp updateUser(@RequestBody User user,Long userId){
		log.debug("修改用户信息");
		User u =userDao.findOne(userId);
		u.setIdentityFront(user.getIdentityFront());
		u.setLicenseUrl(user.getLicenseUrl());
		u.setRealName(user.getRealName());
		u.setStoreUrl(user.getStoreUrl());
		u.setIdentityBack(user.getIdentityBack());
		u.setHeadUrl(user.getHeadUrl());
		u.setIdCard(user.getIdCard());
		u.setNickName(user.getNickName());
		u.setPassword(user.getPassword());
		u.setSecondId(user.getSecondId());
		u.setShopStartMoney(user.getShopStartMoney());
		u.setShopStartTime(user.getShopStartTime());
		u.setSex(user.getSex());
		//u.setServeType(user.getServeType());
		u.setPhone(user.getPhone());
		u.setDailyTasks(user.getDailyTasks());
		u.setOrderTicket(user.getOrderTicket());
		u.setDailyDeduction(user.getDailyDeduction());
		u.setServiceRate(user.getServiceRate());
		u.setRestDays(user.getRestDays());
		u.setChangeDays(user.getChangeDays());
		u.setWorktimeMon(user.getWorktimeMon());
		u.setWorktimeEve(user.getWorktimeEve());
		u.setFullTime(user.getFullTime());
		u.setIsMorning(user.getIsMorning());
		userDao.save(u);
		return JsonResp.ok();
	}

	/**
	 * @指派订单给骑手（手动）
	 *
	 * @return 返回值JsonResp
	 */
	@RequestMapping(value = "/sendOrderToRider",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp sendOrderToRider(Long rideId,Long orderId) throws Exception {
		log.debug("指派订单给骑手（手动）");
		User ride= userDao.findOne(rideId);
		Order order = orderDao.findOne(orderId);
		Account account =accountDao.findByUser(ride);
		Double goodsMoney=order.getGoodsMoney();//货价
//		Double  takeMoney=order.getTakeMoney();//代收货款
		//   BigDecimal totalMoney=new BigDecimal(goodsMoney).add(new BigDecimal(takeMoney));
		if(goodsMoney.compareTo(account.getDepositMoney())>0 || account.getDepositMoney().compareTo(200D)<0){
			return JsonResp.fa("押金低于该订单的最低要求押金数额，指派订单失败");
		}else{
			if (order.getOrderStatus() == 1) {//如果订单状态为待抢单
				order.setRide(ride);
				order.setOrderStatus(2);//更改为待取货
				order.setRobDatetime(new Date());//骑手抢单时间
				Long s=new Date().getTime()+order.getLimitTime()*60*1000;
				String sendTimeStr=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(s);
				try {
					order.setSendTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sendTimeStr));//保存规定送达时间
					orderDao.save(order);
				} catch (ParseException e) {
					e.printStackTrace();
					log.debug("时间转换出错！");
				}
				//从押金中扣除货物价格
				account.setDepositMoney(new BigDecimal(account.getDepositMoney()).subtract(new BigDecimal(goodsMoney)).doubleValue());
				account.setBlockDepositMoney(new BigDecimal(account.getDepositMoney()).add(new BigDecimal(goodsMoney)).doubleValue());
				accountDao.save(account);
				/****************************账户资金流水明细（扣除押金） 骑手*****************************/
				CashRecord cashRecord=new CashRecord();
				cashRecord.setUser(ride);
				cashRecord.setTitle("指派订单成功交付押金"+goodsMoney+"元");
				cashRecord.setOrderType(1);//配送订单
				cashRecord.setOrderNumber(order.getOrderNumber());
				cashRecord.setRecoedType(3);//配送订单得钱
				cashRecord.setMoneyType(2);
				cashRecord.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
				cashRecord.setMoney(-goodsMoney);
				cashRecord.setStatus(1);//成功
				cashRecord.setGivePerson(2);
				cashRecord.setReceivePerson(2);
				cashRecordDao.save(cashRecord);
				String time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
	/*			//激光推送 发送抢单成功消息至骑手
				List<String> aliasList=new ArrayList<>();
				aliasList.add(ride.getAlias());
				String msg_content="您于"+time+"成功抢到一条订单，请尽快前往提货地点提取。";
				JSONObject jsonObject=new JSONObject();
				jsonObject.put("type",1);
				jsonObject.put("id",order.getId());
				int n=JpushClientUtil.sendToAliasId(aliasList,"抢单通知","抢单成功",msg_content,jsonObject.toString());*/
				//激光推送 发送抢单成功消息至商家
				List<String> aliasList=new ArrayList<>();
                aliasList.add(order.getRide().getAlias());
				String msg_content2="骑手于"+time+"成功被指派一条订单，请保持电话畅通。";
				JSONObject jsonObject2=new JSONObject();
				jsonObject2.put("type",12);
				jsonObject2.put("id",order.getId());
				int m= JpushClientUtil.sendToAliasId(aliasList,"指派订单通知","指派订单成功",msg_content2,jsonObject2.toString());
				log.debug("推送状态"+m);
				//短信推送用户
				String phone=order.getAddressUser().getPhone();
				JSONArray phones=new JSONArray();
				phones.put(phone);
				String templateid ="3060370";//指派订单成功
				if(phone!=null){
					try {
						SmsUtils.sendMsg(phones,templateid,null,2);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			} else {
				return JsonResp.fa("该订单已被指派!");
			}
		}
		return JsonResp.ok("指派订单成功");
	}

	/**
	 * @指派订单给骑手（系统指派）
	 *
	 * @return 返回值JsonResp
	 */
/*	@RequestMapping(value = "/sendOrderToRiderBySystem",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")*/
	public JsonResp sendOrderToRiderBySystem() throws Exception {
		log.debug("派订单给骑手（系统指派）");
		//得到所有骑手坐标
		String sql=" SELECT c.* FROM(SELECT a.* FROM dynamic_place a INNER JOIN (SELECT MAX(id) id,ride_id FROM dynamic_place GROUP BY ride_id)b ON a.ride_id=b.ride_id AND a.id=b.id ORDER BY a.ride_id) as c INNER JOIN  user u WHERE c.ride_id=u.id and u.is_work=1 and u.user_status=1 ";
		List<DynamicPlace> resultList = (List<DynamicPlace>) sqlToResult.getResultList(sql);
		List<Map> list = new ArrayList<>();
		for (Object dynamicPlace : resultList) {
			Map map = PubLib.copyObject(dynamicPlace, Map.class);
			list.add(map);
		}
		if (list.size()==0){
			return JsonResp.ok("当前无骑手");
        }else{
			//找到指派时间
			List<CallSetting> callSettingList = callSettingDao.findAll();
			CallSetting callSetting = callSettingList.get(0);
			Integer minute = callSetting.getCallTime();
            //获取所有指派订单id
			String sql2=" SELECT id FROM orders WHERE order_status=1 AND (SELECT(UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(gmt_datetime)) / 60) > "+minute+"";
			List<DynamicPlace> resultList2 = (List<DynamicPlace>) sqlToResult.getResultList(sql2);
			List<Map> list2= new ArrayList<>();
			for (Object dynamicPlace : resultList2) {
				Map map = PubLib.copyObject(dynamicPlace, Map.class);
				list2.add(map);
			}

			if(list2.size()==0){
				return JsonResp.ok("当前无指派订单");
			}else{
				List<Order> orderList = new ArrayList<>();
				for(Map p:list2){
					Order order= orderDao.findOne(Long.parseLong(p.get("id").toString()));
					orderList.add(order);
				}
				//遍历所有订单
				for(Order order:orderList){
					String destination=order.getAddressUser().getLng()+","+order.getAddressUser().getLat();
					//筛选出所有押金足够且没被处罚的骑手
					List<Map> rideList = new ArrayList<>();
					for(Map map:list){
						Long rideId=Long.parseLong(map.get("rideId").toString());
						User ride = userDao.findOne(rideId);
						Integer servreType = ride.getServeType();
						Account account =accountDao.findByUser(ride);
						Double goodsMoney=order.getGoodsMoney();//货价
						//押金足够时放入rideList中
						if(goodsMoney.compareTo(account.getDepositMoney())<0 && account.getDepositMoney().compareTo(200D)>0&&servreType==1){
							rideList.add(map);
						}
					}

					//拿到骑手所有坐标
					String origins ="";
					for(int i=0;i<rideList.size();i++){
						if(i==rideList.size()-1){
							origins += rideList.get(i).get("lng").toString()+","+rideList.get(i).get("lat").toString();
						}else{
							origins += rideList.get(i).get("lng").toString()+","+rideList.get(i).get("lat").toString()+"|";
						}
					}
					//调用api获得距离集合
					List<String> distance=MapUtils.manyDistance(origins,destination);
					//把距离加入list里
					for (int i=0;i<distance.size();i++){
						rideList.get(i).put("distance",distance.get(i));
					}
					//将距离排序
					Collections.sort(rideList, new Comparator<Map>(){
						@Override
						public int compare(Map o1, Map o2) {
							if(Integer.parseInt(o1.get("distance").toString()) > Integer.parseInt(o2.get("distance").toString()) ){
								return 1;
							}
							if(Integer.parseInt(o1.get("distance").toString()) == Integer.parseInt(o2.get("distance").toString())){
								return 0;
							}
							return -1;
						}
					});
					//找到设置前几的人数
					Integer person = callSetting.getPerson();
					//找出前person个
					List<Map> rides= new ArrayList<>();
					for (int i=0;i<rideList.size();i++){
						rides.add(rideList.get(i));
						if(i==person){
							break;
						}
					}
					//找出订单量最少的
					for(Map p1:rides){
						String sqltwo=" SELECT ifnull(count(id),0) as sum FROM orders where order_status in(2,3) and ride="+Long.parseLong(p1.get("rideId").toString()) +" ";
						Object resultListtwo = sqlToResult.getResultList(sqltwo, "one");
						Map map = PubLib.copyObject(resultListtwo, Map.class);
						p1.put("sum",map.get("sum"));
					}
					//将订单量排序
					Collections.sort(rides, new Comparator<Map>(){
						@Override
						public int compare(Map o1, Map o2) {
							if(Integer.parseInt(o1.get("sum").toString()) > Integer.parseInt(o2.get("sum").toString()) ){
								return 1;
							}
							if(Integer.parseInt(o1.get("sum").toString()) == Integer.parseInt(o2.get("sum").toString())){
								return 0;
							}
							return -1;
						}

					});
					//拿到最终骑手
					Long rideId=Long.parseLong(rides.get(0).get("rideId").toString());
					User ride = userDao.findOne(rideId);

					Account account =accountDao.findByUser(ride);
					Double goodsMoney=order.getGoodsMoney();//货价
//		Double  takeMoney=order.getTakeMoney();//代收货款
					//   BigDecimal totalMoney=new BigDecimal(goodsMoney).add(new BigDecimal(takeMoney));
					if(goodsMoney.compareTo(account.getDepositMoney())>0 || account.getDepositMoney().compareTo(200D)<0){
						return JsonResp.fa("骑手押金不足");
					}else{
						if (order.getOrderStatus() == 1) {//如果订单状态为待抢单
							order.setRide(ride);
							order.setOrderStatus(2);//更改为待取货
							order.setRobDatetime(new Date());//骑手抢单时间
							Long s=new Date().getTime()+order.getLimitTime()*60*1000;
							String sendTimeStr=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(s);
							try {
								order.setSendTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sendTimeStr));//保存规定送达时间
								orderDao.save(order);
							} catch (ParseException e) {
								e.printStackTrace();
								log.debug("时间转换出错！");
							}
							//从押金中扣除货物价格
							account.setDepositMoney(new BigDecimal(account.getDepositMoney()).subtract(new BigDecimal(goodsMoney)).doubleValue());
							account.setBlockDepositMoney(new BigDecimal(account.getDepositMoney()).add(new BigDecimal(goodsMoney)).doubleValue());
							accountDao.save(account);
							/****************************账户资金流水明细（扣除押金） 骑手*****************************/
							CashRecord cashRecord=new CashRecord();
							cashRecord.setUser(ride);
							cashRecord.setTitle("指派订单成功交付押金"+goodsMoney+"元");
							cashRecord.setOrderType(1);//配送订单
							cashRecord.setOrderNumber(order.getOrderNumber());
							cashRecord.setRecoedType(3);//配送订单得钱
							cashRecord.setMoneyType(2);
							cashRecord.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
							cashRecord.setMoney(-goodsMoney);
							cashRecord.setStatus(1);//成功
							cashRecord.setGivePerson(2);
							cashRecord.setReceivePerson(2);
							cashRecordDao.save(cashRecord);
							String time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
	/*			//激光推送 发送抢单成功消息至骑手
				List<String> aliasList=new ArrayList<>();
				aliasList.add(ride.getAlias());
				String msg_content="您于"+time+"成功抢到一条订单，请尽快前往提货地点提取。";
				JSONObject jsonObject=new JSONObject();
				jsonObject.put("type",1);
				jsonObject.put("id",order.getId());
				int n=JpushClientUtil.sendToAliasId(aliasList,"抢单通知","抢单成功",msg_content,jsonObject.toString());*/
							//激光推送 发送抢单成功消息至商家
							List<String> aliasListShop=new ArrayList<>();
							aliasListShop.add(order.getRide().getAlias());
							String msg_content2="骑手于"+time+"成功被指派一条订单，请保持电话畅通。";
							JSONObject jsonObject2=new JSONObject();
							jsonObject2.put("type",11);
							jsonObject2.put("id",order.getId());
							int m= JpushClientUtil.sendToAliasId(aliasListShop,"指派订单通知","指派订单成功",msg_content2,jsonObject2.toString());
							log.debug("推送状态"+m);
							//短信推送用户
							String phone=order.getAddressUser().getPhone();
							JSONArray phones=new JSONArray();
							phones.put(phone);
							String templateid ="3060370";//指派订单成功
							if(phone!=null){
								try {
									SmsUtils.sendMsg(phones,templateid,null,2);
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						} else {
							return JsonResp.fa("该订单已被指派!");
						}
					}

				}
			}
			return JsonResp.ok("指派订单成功");
        }

	}

	@RequestMapping(value = "/startTask",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp getIndex(String urlParameter) {
		Runnable runnable = new Runnable() {
			public void run() {
				// task to run goes here
//				System.out.println("Hello !!");
				try {
					sendOrderToRiderBySystem();
				} catch (Exception e) {
					throw new FailException("调用系统指派订单方法出错！");
				}
			}
		};
		     service = Executors
				.newSingleThreadScheduledExecutor();
		// 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间
		service.scheduleAtFixedRate(runnable, 1, 60, TimeUnit.SECONDS);
		return JsonResp.ok("系统指派订单成功");

	}

	@RequestMapping(value = "/shutDownTask",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp shutDownTask() {
		if(service==null){
			return JsonResp.ok("开启手动指派!");
		}else{
			service.shutdown();
			if(service.isShutdown()){
				return JsonResp.ok("系统指派成功关闭!");
			}else {
				return  JsonResp.fa("关闭失败");
			}
		}
	}

	/**
	 * @获取微信当前登陆者的位置信息
	 *
	 * @return 返回值JsonResp
	 */
/*	@RequestMapping(value = "/getLoginUserPlace",
			method = RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	public JsonResp getIndex(String urlParameter){
           Map map2=new HashMap();
		//ModelAndView mav = new ModelAndView("index");
		//获取access_token
		Map<String, String> params = new HashMap<String, String>();
		params.put("corpid","wx7099477f2de8aded");
		params.put("corpsecret","4clWzENvHVmpcyuA4toys0URkfYanIqWtxZ5plbisn6Cd5AVTF0thpaK6UAhjIvN");
		String xml = HttpXmlClient.post("https://qyapi.weixin.qq.com/cgi-bin/gettoken",params);
		JSONObject jsonMap  = net.sf.json.JSONObject.fromObject(xml);
		Map<String, String> map = new HashMap<String, String>();
		Iterator<String> it = jsonMap.keys();
		while(it.hasNext()) {
			String key = (String) it.next();
			String u = jsonMap.get(key).toString();
			map.put(key, u);
		}
		String access_token = map.get("access_token");

		//获取ticket
		params.put("access_token",access_token);
		xml = HttpXmlClient.post("https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket",params);
		jsonMap  = JSONObject.fromObject(xml);
		map = new HashMap<String, String>();
		it = jsonMap.keys();
		while(it.hasNext()) {
			String key = (String) it.next();
			String u = jsonMap.get(key).toString();
			map.put(key, u);
		}
		String jsapi_ticket = map.get("ticket");

		//获取签名signature
		String noncestr = UUID.randomUUID().toString();
		String timestamp = Long.toString(System.currentTimeMillis() / 1000);
		//获取请求url
	//	String path = request.getContextPath();
		//以为我配置的菜单是http://yo.bbdfun.com/first_maven_project/，最后是有"/"的，所以url也加上了"/"
		//String url = request.getScheme() + "://" + request.getServerName() +  path + "/";
		String str = "jsapi_ticket=" + jsapi_ticket +
					"&noncestr=" + noncestr +
					"&timestamp=" + timestamp +
					"&url=" + urlParameter;
		//sha1加密
		String signature = HttpXmlClient.SHA1(str);
//		mav.addObject("signature", signature);
//		mav.addObject("timestamp", timestamp);
//		mav.addObject("noncestr", noncestr);
//		mav.addObject("appId", "wx7099477f2de8aded");
		map2.put("signature", signature);
		map2.put("timestamp", timestamp);
		map2.put("noncestr", noncestr);
		map2.put("appId", "wx7099477f2de8aded");
		System.out.println("jsapi_ticket=" + jsapi_ticket);
		System.out.println("noncestr=" + noncestr);
		System.out.println("timestamp=" + timestamp);
		System.out.println("url=" + urlParameter);
		System.out.println("str=" + str);
		System.out.println("signature=" + signature);
		return JsonResp.ok(map2);

	}*/




}
